import urllib.request

# 肯德基北京店一共 64页
METHOD = 'POST'
BASE_URL = 'http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname'
HEADER = {
    'Host': 'www.kfc.com.cn',
    'Connection': 'keep-alive',
    'Content-Length': '53',
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'X-Requested-With': 'XMLHttpRequest',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Origin': 'http://www.kfc.com.cn',
    'Referer': 'http://www.kfc.com.cn/kfccda/storelist/index.aspx',
    # 'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Cookie': 'route-cell=ksa; ASP.NET_SessionId=4bnlexgrpx2dteerprzyiz4s; Hm_lvt_5fd8501a4e4e0eddf0c4596de7bd57ab=1657331362; Hm_lvt_1039f1218e57655b6677f30913227148=1657331362; Hm_lpvt_1039f1218e57655b6677f30913227148=1657331362; Hm_lpvt_5fd8501a4e4e0eddf0c4596de7bd57ab=1657331378; __utma=62931061.1906034963.1657332523.1657332523.1657332523.1; __utmc=62931061; __utmz=62931061.1657332523.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=62931061.1.10.1657332523; SERVERID=db2965ac6d1d4f093009cf9d5cafcc6f|1657332540|1657331361',
}
PAGE_SIZE = 10


# 函数封装1 创建请求对象
def createRequestObject(pageIndex):
    data = {
        'cname': '北京',
        'pid': '',
        'pageIndex': pageIndex,
        'pageSize': PAGE_SIZE,
    }
    data = urllib.parse.urlencode(data).encode('UTF-8')
    return urllib.request.Request(url=BASE_URL, headers=HEADER, data=data)


# 函数封装2 获取响应的接口数据
def getContent(request):
    response = urllib.request.urlopen(request)
    return response.read().decode('UTF-8')


# 函数封装3 将数据写入磁盘
def writeToDisk(pageIndex, jsonString):
    with open(file=f'KFC-北京店-{pageIndex}.json', mode='w', encoding='UTF-8') as fileOpen:
        fileOpen.write(jsonString)


# 启动标识
if __name__ == '__main__':
    # startPage = int(input('起始页：'))
    # endPage = int(input('结束页：'))
    startPage = 1
    endPage = 64

    for index in range(startPage, endPage + 1):
        requestObject = createRequestObject(index)
        jsonData = getContent(requestObject)
        print(jsonData)
        writeToDisk(index, jsonData)
